//
//  YsCloudFileManageInit.m
//  YsCloudFileManageSDK
//
//  Created by 宋宏康 on 2020/2/25.
//

#import "YsCloudFileManageInit.h"
#import "YsCloudFileUserManage.h"
#import "YsCloudFileManageSDKServer.h"
#import "YsCloudFileRealmManager.h"
#import "YsCloudFileManagerHeader.h"
#import "YsCloudFileManageSDKRealm.h"
#import "YsCloudFileDownloadManager+Tools.h"

@implementation YsCloudFileManageInit

static YsCloudFileManageInit *manager = nil;

+ (instancetype)shareCloudFileManageInit
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

- (void)initSDKNeedAccountCode:(NSString *)needAccountCode withFailBlock:(void(^)(NSError *error))fail
{
    NSParameterAssert(needAccountCode);
    NSParameterAssert(fail);
    /// 初始化needAccountCode
    [YsCloudFileUserManage shareCloudFileUserManage].userModel.accountCode = needAccountCode;
    /// 初始化网络请求
    [YsCloudFileManageSDKServer.shareCloudFileManageSDKServerManager fetchUploadFetchWayWithfail:fail];
    /// 初始化数据库
    [YsCloudFileRealmManager setupConfigWithDirName:@"tmpRealm" withRealmName:@"SmartPen.realm"];
    /// 查询
    [self queryfileCloudData];
    /// 恢复所有的下载的任务
    [YsCloudFileDownloadManager.shareDownloadManger resumeAllRequestBecauseofAppKill];
}

- (void)queryfileCloudData
{
    NSPredicate *query = [NSPredicate predicateWithFormat:@"accountCode == %@",kAccountCode];
    NSUInteger count = [YsCloudFileRealmManager queryObjsWithPredicate:query targetClass:YsCloudFileManageSDKRealm.class].count;
    if (count == 0) { //需要创建YsCloudFileManageSDKRealm的表
        YsCloudFileManageSDKRealm *fileMangeSDKRealm = [[YsCloudFileManageSDKRealm alloc] init];
        fileMangeSDKRealm.accountCode = kAccountCode;
        /// 会自动更新数据
        [YsCloudFileRealmManager writeObj:fileMangeSDKRealm];
    }
}
@end
